/**
 * Created by Adam on 2017/5/16.
 */
import React from 'react'
import {addUser} from '../actions'
import {connect} from 'react-redux'
import {TextField, RaisedButton, MuiThemeProvider} from 'material-ui'
import {Field, reduxForm} from 'redux-form'

export const renderTextField = ({input, label, meta: {touched, error}, ...custom}) => {
    return (
        <TextField
            hintText={label}
            floatingLabelText={label}
            errorText={touched && error}
            {...input}
            {...custom}
        />
    )
}

const AddUserForm = ({handleSubmit, pristine, reset, submitting}) => (
    <MuiThemeProvider>
        <form onSubmit={handleSubmit}>
            <div>
                <Field name="name" label="name" type="text" component={renderTextField}/>
            </div>
            <div>
                <Field name="age" label="age" type="number" component={renderTextField}/>
            </div>
            <div>
                <RaisedButton primary={true} type="submit" label="Add User"/>
            </div>
        </form>
    </MuiThemeProvider>
)

const ReduxAddUserForm = reduxForm({
    form: 'AddUserForm'
})(AddUserForm)

class AddUser extends React.Component {

    submitHandler = (values) => {
        console.log(values)
        const {dispatch} = this.props
        console.log(values.name, values.age)
        dispatch(addUser(values.name, values.age))
    }

    render() {
        return (
            <ReduxAddUserForm onSubmit={this.submitHandler}/>
        )
    }
}

AddUser = connect()(AddUser)

export default AddUser